package com.zy.cat.common.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.SpringApplication;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.taobao.api.internal.util.WebUtils;
import com.zy.cat.entity.dtk.SuperCategory;
import com.zy.cat.entity.dtk.SuperCategory.Category;
import com.zy.cat.entity.dtk.resp.GoodsListResp;
import com.zy.cat.entity.hdk.HdkGoodsItem;
import com.zy.cat.entity.hdk.HdkSuperCategory;
import com.zy.cat.entity.hdk.HdkSuperCategory.Subcats;
import com.zy.cat.entity.mall.resp.CatDouYinVideoResp;
import com.zy.cat.entity.mall.resp.CatHdkDuoyinResp;
import com.zy.cat.entity.mall.resp.CatHdkRatesUrlResp;
import com.zy.cat.entity.mall.resp.CatTalentArticleResp;
import com.zy.cat.entity.mall.resp.CatTalentInfoResp;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.entity.wy.TKConvertResp;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description: TODO(描述)
 * @author xiake
 * @date 2020-08-03 04:15:07
 */
@Slf4j
public class HdkAPI {
	
	//private String apikey = "taotaoji";
	private String apikey = "1A98858DC714";
	
	private String pid = "mm_127127112_1057200437_110734050261";
	
	private String tb_name = "zjcails1314";
	
	private String url="http://v2.api.haodanku.com/";
	
	
	private static HdkAPI hdkAPI;
	
	public static HdkAPI getInstance() {
		if (hdkAPI==null) {
			hdkAPI=new HdkAPI();
		}
		return hdkAPI;
	}
	
	
	public CatHdkRatesUrlResp ratesurl(String itemId) {
		// JAVA请求示例：
		String result = null;
		String urlString = url+"ratesurl";
		InputStream is = null;
		String param = null;
		StringBuilder sbParams = new StringBuilder();
		sbParams.append("apikey");
		sbParams.append("=");
		sbParams.append(apikey);
		sbParams.append("&");
		sbParams.append("itemid");
		sbParams.append("=");
		sbParams.append(itemId);
		sbParams.append("&");
		sbParams.append("pid");
		sbParams.append("=");
		sbParams.append(pid);
		sbParams.append("&");
		sbParams.append("tb_name");
		sbParams.append("=");
		sbParams.append(tb_name);
		sbParams.append("&");
		try {
			URL url = new URL(urlString);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			// post请求需要设置DoOutput为true
			urlConnection.setDoOutput(true);
			urlConnection.setRequestMethod("POST");
			// 设置参数
			param = sbParams.toString();
			urlConnection.getOutputStream().write(param.getBytes());
			urlConnection.getOutputStream().flush();
			urlConnection.setConnectTimeout(5 * 1000);
			urlConnection.setReadTimeout(5 * 1000);
			// 连接服务器
			urlConnection.connect();
			StringBuilder stringBuilder = new StringBuilder();
			if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				is = urlConnection.getInputStream();
				int len = 0;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer)) != -1) {
					stringBuilder.append(new String(buffer, 0, len));
				}
				result = stringBuilder.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.out.println(result);
		if (result!=null) {
			String string = JSON.parseObject(result).getString("data");
			if (!StringUtils.isEmpty(string)) {
				return JSON.parseObject(string, CatHdkRatesUrlResp.class);
			}
		}
		return null;
	}
		
	/**
	 * 获取超级分类
	 * @author lipengchao
	 * @date 2020-08-19 03:02:07
	 */
	public List<HdkSuperCategory> getSuperClassify() {
		String urlString = url+"super_classify"+"/apikey/"+apikey;
		try {
			String json = WebUtils.doGet(urlString, null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				JSONArray jsonArray = jsonObject.getJSONArray("general_classify");
				List<HdkSuperCategory> list = JSON.parseArray(jsonObject.getString("general_classify"),HdkSuperCategory.class);
				if (list!=null && list.size()>0) {
					list.forEach(category->{
						category.setSubcats(new ArrayList<>());
						for (HdkSuperCategory.SubcatsParent superCategory : category.getData()) {
							List<Subcats> parseArray = JSON.parseArray(superCategory.getInfo(), HdkSuperCategory.Subcats.class);
							category.getSubcats().addAll(parseArray);
						}
					});
				}
				return list;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 关键词商品页API
	 * @author lipengchao
	 * @date 2020-08-19 05:43:27 
	 * @param keyword 搜索关键词 支持宝贝ID搜索即keyword=itemid（由于存在特殊符号搜索的关键词必须进行两次urlencode编码）
	 * @param sort 0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额，4.销量，5.佣金比例，6.券面额（低到高），7.月销量（低到高），8.佣金比例（低到高），9.全天销量（高到低），10全天销量（低到高），11.近2小时销量（高到低），12.近2小时销量（低到高），13.优惠券领取量（高到低），14.好单库指数（高到低）
	 * @param min_id 分页
	 * @param back 每页返回条数
	 * @param cid 0全部，1女装，2男装，3内衣，4美妆，5配饰，6鞋品，7箱包，8儿童，9母婴，10居家，11美食，12数码，13家电，14其他，15车品，16文体
	 */
	public ResultPage<HdkGoodsItem> getKeywordItems(String keyword,int sort,int min_id,int back,int cid) {
		Map<String, String> param=new HashMap<String, String>();
		param.put("apikey", apikey);
		try {
			keyword=URLEncoder.encode(URLEncoder.encode(keyword,"utf-8"),"utf-8");
			param.put("keyword", keyword);
			param.put("back", back+"");
			param.put("sort", sort+"");
			param.put("min_id", min_id+"");
			param.put("cid", cid+"");
			
			StringBuilder sbParams = new StringBuilder(url+"get_keyword_items/");
			param.forEach((key,value)->{
				sbParams.append(key+"/"+value+"/");
			});
			String json = WebUtils.doGet(sbParams.toString(), null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				ResultPage<HdkGoodsItem> page=new ResultPage<>(min_id, back);
				page.setTotal(Integer.parseInt(jsonObject.getString("total")));
				List<HdkGoodsItem> list = JSON.parseArray(jsonObject.getString("data"),HdkGoodsItem.class);
				if (list!=null && list.size()>0) {
					list.forEach(item->{
						item.setFcode(CalculateUtil.getRebateAmount(Double.parseDouble(item.getItemendprice()), Double.parseDouble(item.getTkrates())));
					});
				}
				page.setList(list);
				return page;
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("查询好单库关键词分页错误:"+e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 达人说API
	 * @author lipengchao
	 * @param talentcat 大家都在逛类目，文章类别（0.全部，1.好物,2.潮流,3.美食,4.生活）
	 * @date 2020-08-31 03:02:07
	 */
	public CatTalentInfoResp getTalentInfo(int talentcat) {
		String urlString = url+"talent_info"+"/apikey/"+apikey+"/talentcat/"+talentcat;
		try {
			String json = WebUtils.doGet(urlString, null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				JSONObject jsonObj = jsonObject.getJSONObject("data");
				CatTalentInfoResp infoResp = JSON.parseObject(jsonObject.getString("data"), CatTalentInfoResp.class);
				infoResp.setTalentCategory(JSON.parseObject(jsonObj.getString("talent_Category"), new TypeReference<Map<String,String>>(){}));
				return infoResp;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 达人说文章详情API
	 * @author lipengchao
	 * @param id 文章ID
	 * @date 2020-08-31 03:02:07
	 */
	public CatTalentArticleResp getTalentArticle(Integer id) {
		String urlString = url+"talent_article"+"/apikey/"+apikey+"/id/"+id;
		try {
			String json = WebUtils.doGet(urlString, null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTalentArticle-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				JSONObject jsonObj = jsonObject.getJSONObject("data");
				CatTalentArticleResp infoResp = JSON.parseObject(jsonObject.getString("data"), CatTalentArticleResp.class);
				if (infoResp!=null && infoResp.getItems().size()>0) {
					infoResp.getItems().forEach(item->{
						item.setFcode(CalculateUtil.getRebateAmount(Double.parseDouble(item.getItemendprice()), Double.parseDouble(item.getTkrates())));
					});
				}
				return infoResp;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 商品列表页API
	 * @author lipengchao
	 * @date 2020-08-31 05:43:27 
	 * @param nav 默认是全部商品1（1实时跑单商品，2爆单榜商品，3全部商品，4纯视频单，5聚淘专区）
	 * @param sort 	0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额（高到低），4.月销量（高到低），5.佣金比例（高到低），6.券面额（低到高），7.月销量（低到高），8.佣金比例（低到高），9.全天销量（高到低），10全天销量（低到高），11.近2小时销量（高到低），12.近2小时销量（低到高），13.优惠券领取量（高到低）
	 * @param min_id 分页
	 * @param back 每页返回条数
	 * @param cid 0全部，1女装，2男装，3内衣，4美妆，5配饰，6鞋品，7箱包，8儿童，9母婴，10居家，11美食，12数码，13家电，14其他，15车品，16文体，17宠物
	 */
	public ResultPage<HdkGoodsItem> getItemlist(int nav,int sort,int min_id,int back,int cid) {
		Map<String, String> param=new HashMap<String, String>();
		param.put("apikey", apikey);
		try {
			param.put("nav", nav+"");
			param.put("back", back+"");
			param.put("sort", sort+"");
			param.put("min_id", min_id+"");
			param.put("cid", cid+"");
			
			StringBuilder sbParams = new StringBuilder(url+"itemlist/");
			param.forEach((key,value)->{
				sbParams.append(key+"/"+value+"/");
			});
			String json = WebUtils.doGet(sbParams.toString(), null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				ResultPage<HdkGoodsItem> page=new ResultPage<>(min_id, back);
//				page.setTotal(Integer.parseInt(jsonObject.getString("total")));
				List<HdkGoodsItem> list = JSON.parseArray(jsonObject.getString("data"),HdkGoodsItem.class);
				if (list!=null && list.size()>0) {
					list.forEach(item->{
						item.setFcode(CalculateUtil.getRebateAmount(Double.parseDouble(item.getItemendprice()), Double.parseDouble(item.getTkrates())));
					});
				}
				page.setList(list);
				return page;
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("查询好单库关键词分页错误:"+e.getMessage());
		}
		return null;
	}
	
	/**
	 * 抖音数据API
	 * @author lipengchao
	 * @date 2020-09-01 08:58:27 
	 * @param itemid 商品ID
	 * @param min_id 分页
	 */
	public List<CatDouYinVideoResp> getDouyinItems(String itemid,int min_id) {
		Map<String, String> param=new HashMap<String, String>();
		param.put("apikey", apikey);
		try {
			param.put("itemid", itemid+"");
			param.put("min_id", min_id+"");
			
			StringBuilder sbParams = new StringBuilder(url+"douyin_items/");
			param.forEach((key,value)->{
				sbParams.append(key+"/"+value+"/");
			});
			String json = WebUtils.doGet(sbParams.toString(), null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				if (jsonObject.getJSONArray("data").size()==0) {
					return null;
					
				}
				List<CatDouYinVideoResp> resp=JSON.parseArray(jsonObject.getString("data"), CatDouYinVideoResp.class);
				return resp;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("查询好单库抖音数据错误:"+e.getMessage());
		}
		return null;
	}
	
	
	/**
	 * 查询好单库排行榜
	 * @author lipengchao
	 * @date 2020-09-23 04:13:34 
	 * @param stype
	 * @param cid
	 * @param min_id
	 * @param back
	 * @param item_type
	 * @return
	 */
	public List<HdkGoodsItem> getGoodsRank(Integer stype, Integer cid, Integer min_id, Integer back, Integer item_type) {
		HdkGoodsItem result=null;
		Map<String,String> param=new HashMap<String, String>();
		param.put("apikey", apikey);
		param.put("sale_type",""+stype);
		
		if(cid!=null&&cid>=0) {
			param.put("cid",""+cid);
		}
		if(min_id!=null&&min_id>=0) {
		param.put("min_id",""+min_id);
		}
		if(back!=null&&back>=0) {
		param.put("back",""+back);
		}
		if(item_type!=null&&item_type>=0) {
		param.put("item_type",""+item_type);
		}
		StringBuilder sbParams = new StringBuilder(url+"sales_list/");
		param.forEach((key,value)->{
			sbParams.append(key+"/"+value+"/");
		});
		String json;
		try {
			json = WebUtils.doGet(sbParams.toString(), null);
			log.info("-getGoodsRank-->{}",json);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				if (jsonObject.getJSONArray("data").size()==0) {
					return null;
				}
				List<HdkGoodsItem> resp=JSON.parseArray(jsonObject.getString("data"), HdkGoodsItem.class);
				return resp;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 抖货商品API
	 * @author lipengchao
	 * @date 2020-09-01 08:58:27 
	 * @param itemid 商品ID
	 * @param min_id 分页
	 */
	public List<CatHdkDuoyinResp> getHdkDuoyinData(Integer cat_id, Integer min_id, Integer back) {
		Map<String, String> param=new HashMap<String, String>();
		param.put("apikey", apikey);
		try {
			param.put("cat_id", cat_id+"");
			param.put("min_id", min_id+"");
			param.put("back", back+"");

			StringBuilder sbParams = new StringBuilder(url+"get_trill_data/");
			param.forEach((key,value)->{
				sbParams.append(key+"/"+value+"/");
			});
			String json = WebUtils.doGet(sbParams.toString(), null);
			if (StringUtils.isNotBlank(json)) {
				log.info("-getTKConvert-->" + json);
				JSONObject jsonObject = JSON.parseObject(json);
				if (jsonObject.getJSONArray("data").size()==0) {
					return null;
					
				}
				List<CatHdkDuoyinResp> resp=JSON.parseArray(jsonObject.getString("data"), CatHdkDuoyinResp.class);
				if (resp!=null && resp.size()>0) {
					resp.forEach(item->{
						item.setFcode(CalculateUtil.getRebateAmount(Double.parseDouble(item.getItemendprice()), Double.parseDouble(item.getTkrates())));
					});
				}
				return resp;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("查询好单库抖音数据错误:"+e.getMessage());
		}
		return null;
	}
	
	

	public static void main(String[] args) {
		HdkAPI instance = getInstance();
//		List<HdkSuperCategory> list = instance.getSuperClassify();
//		ResultPage<HdkGoodsItem> resultPage = instance.getKeywordItems("鞋品", 0, 1, 20, 6);
//		System.out.println(JSON.toJSONString(resultPage));
//		CatTalentInfoResp talentInfo = instance.getTalentInfo(0);
//		System.out.println(JSON.toJSONString(talentInfo));
//		ResultPage<HdkGoodsItem> resultPage = instance.getItemlist(4, 0, 1, 20, 6);
//		System.out.println(JSON.toJSONString(resultPage));
		
		List<CatDouYinVideoResp> list = instance.getDouyinItems("596098430467", 1);
		System.out.println(JSON.toJSONString(list));
	}
}
